package woa.sort;

import java.util.Arrays;

/**
 * 归并排序
 *
 * @author wangpeng
 * @date 2022/1/10
 */
public class MergeSort {

    public static void sort(int[] arr, int start, int end) {
        if (start >= end) {
            return;
        }
        int mid = start + (end - start) / 2;
        sort(arr, start, mid);
        sort(arr, mid + 1, end);
        merge(arr, start, mid, end);
    }

    public static void merge(int[] arr, int p, int q, int r) {
        int i = p;
        int j = q + 1;
        int k = 0;
        int[] temp = new int[r - p + 1];
        while (i <= q && j <= r) {
            if (arr[i] < arr[j]) {
                temp[k] = arr[i];
                i++;
            } else {
                temp[k] = arr[j];
                j++;
            }
            k++;
        }

        //是否有剩余数据需要处理
        int start = i;
        int end = q;
        if (j <= r) {
            start = j;
            end = r;
        }
        for (; start <= end; start++) {
            temp[k] = arr[start];
            k++;
        }

        // 将tmp中的数组拷贝回a[p...r]
        for (i = 0; i <= r - p; ++i) {
            arr[p + i] = temp[i];
        }
    }

    public static void main(String[] args) {
        int[] arr = new int[]{4,3,1,2,71};
        sort(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }
}
